<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<script type="text/javascript">
    var userBuckets = {};
    var dataTable = null;
    var setting = {
        data: {
            key: {
                title: "t"
            },
            simpleData: {
                enable: true
            }
        },
        view: {
            selectedMulti: false
        },
        callback: {
            onClick: onClick,
            onAsyncError: onAsyncError
        }
    };

    function onClick(event, treeId, treeNode, clickFlag) {
        $("#m_orgId").val(treeNode.id);
        $("#m_branchId").val(treeNode.t);
        $("#m_orgName").val(treeNode.name);
        changePost();
    }

    var zTreeNodes = ${zTreeNodes};


    function addUser(id) {
        $("#m_userId").val("");
        $("#m_userCode").val("");
        $("#m_fullName").val("");
        $("#m_loginName").val("");
        $("#m_phone").val("");
        //$("#m_orgId").val("");
        // $("#m_orgCode").val("");
        // $("#m_orgName").val("");
        // $("#m_post ").empty();
        $("#m_branchId").val("");
        $(".userValidateTips").text("");        
        $("#user-dialog-form").dialog("open");
    }

    function editUser(id) {
        $("#m_userId").val(id);
        $(".userValidateTips").text("");
        $.ajax({
            url: "${ctx}/system/user/" + id,
            data: {"random": new Date().getTime()},
            dataType: "json",
            success: function (data) {
                $("#m_userCode").val(data.userCode);
                $("#m_fullName").val(data.fullName);
                $("#m_loginName").val(data.loginName);
                $("#m_phone").val(data.phone);
                if(data.branchId != null && data.id != ""){
                	$("#m_branchId").find("option[value="+data.branchId+"]").attr("selected",true);
                } else {
                	$("#m_branchId").val("");
                }
                if(data.userStatus != null && data.userStatus != ""){
                    if( data.userStatus=="1") {
                        $("#m_userStatus").find("option[value=1]").attr("selected", true);
                    }else{
                        $("#m_userStatus").find("option[value=2]").attr("selected", true);
                    }
                } else {
                	$("#m_userStatus").val("");
                }
                
                // $("#m_orgId").val(data.orgId);
                // $("#m_orgCode").val(data.orgCode);
                // $("#m_orgName").val(data.orgName);
                /*
                $.ajax({
                    url: "${ctx}/system/post/" + data.orgId,
                    data: {"random": new Date().getTime()},
                    dataType: "json",
                    success: function (labelValues) {
                        $("#m_post ").empty();
                        for(i = 0; i < labelValues.length; i++) {
                            if(labelValues[i].value == data.postId) {
                                $("#m_post ").append("<option value='" + labelValues[i].value + "' selected>" + labelValues[i].label + "</option>");
                            } else {
                                $("#m_post ").append("<option value='" + labelValues[i].value + "'>" + labelValues[i].label + "</option>");
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        onAsyncError();
                    }
                });
                */
               $("#user-dialog-form").dialog("open");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                onAsyncError();
            }
        })
    }

    function changePost() {
        $.ajax({
            url: "${ctx}/system/post/" + $("#m_orgId").val(),
            data: {"random": new Date().getTime()},
            dataType: "json",
            success: function (labelValues) {
                $("#m_post ").empty();
                for(i = 0; i < labelValues.length; i++) {
                    $("#m_post ").append("<option value='" + labelValues[i].value + "'>" + labelValues[i].label + "</option>");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                onAsyncError();
            }
        })
    }

    function roleAssign(id) {
        $("#m_userId").val(id);
        $("#m_hRoleIds").val("");
        $("input[name='m_roleIds']").removeAttr("checked");

        $.ajax({
            url: "${ctx}/system/user/role/" + $("#m_userId").val(),
            data: {"random": new Date().getTime()},
            dataType: "json",
            success: function (roles) {
                for(i = 0; i < roles.length; i++) {
                    $("input[name='m_roleIds']").each(function(){
                        if($(this).val() == roles[i]) {
                            $(this).attr("checked", "true");
                        }
                    });
                }
               // $("#role-dialog-form").dialog("open");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                onAsyncError();
            }
        })
    }

    function onAsyncError() {
        $("#dialogMessage").text("Network issue, please contact administrator!");
        //$("#dialog-message").dialog("open");
    }

    function checkDuplicate(loginName) {
        if(loginName != '') {
            $.ajax({
                url: "${ctx}/system/user/duplicate/" + loginName,
                data: {"random": new Date().getTime()},
                success: function (data) {
                    if(data != '' && data != $("#m_userId").val()) {
                        $(".userValidateTips").text("登陆名称重复，请重新输入.");
                        $("#m_loginName").focus();
                        return false;
                    } else {
                        $(".userValidateTips").text("");
                        return true;
                    }
                }
            });
        }
    }
    
    function showMenu() {
        var cityObj = $("#m_branchId");
        var cityOffset = cityObj.offset();
        $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px",zIndex:9999}).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }

    function onBodyDown(event) {
        if (!(event.target.id == "menuBtn" || event.target.id == "m_orgDesc" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
            hideMenu();
        }
    }

    function hideMenu() {
        $("#menuContent").fadeOut("fast");
        $("body").unbind("mousedown", onBodyDown);
    }
    //=========================MJWL START======================
    
    function refreshUserList(){
        $("#userList").jqGrid('setGridParam',{postData:$("#userForm").serializeObject()}).trigger("reloadGrid");
    }

    function roleLink(userId){
        var uId=${userId};
        if(userId!=uId){
            return  tagLink("assignRole("+userId+")", "分配角色")
        }
        return "";
    }

    $(function () {
        $("#btn_search").bind("click", function(){
        	refreshUserList();
        });

        $("#userList").jqGrid({
            datatype: "json",
            url : "${ctx}/system/user/queryUsers",
			mtype: "POST",
            width:"100%",
            height:"100%",
            colNames: ['操作','用户全名','登陆名称', '角色名称', '从属机构'],
            colModel: [
                {name:'act',index:'userId',search:false,sortable:false,editable:false
                    ,formatter:function(cellvalue, options, rowObject){ return tagLinkEdit("editUser("+rowObject.userId+")")+" "+tagLinkDel("deleteUser("+rowObject.userId+")")+" "+roleLink(rowObject.userId)+" "+tagLink("resetPassword("+rowObject.userId+")", "重置密码");}
                },
                {name: 'fullName', index: 'fullName',sortable:false},
                {name: 'loginName', index: 'loginName',sortable:false},
                {name: 'roleName', index: 'roleName',sortable:false},
                {name: 'branchName', index: 'branchName',sortable:false}
            ],
            rowNum: 10,
            rowList:[10,20,30],
            pager: '#pager',
            imgpath: 'images',
            sortname: 'userId',
            viewrecords: true,
            sortorder: "desc",
            autowidth:true,
            jsonReader: {
                repeatitems : false,
                id: "userId"
            },
            caption: "用户查询结果列表"
        });
        
        $("#user-dialog-form").dialog({
            autoOpen: false,
            width: 500,
            modal: true,
            buttons: {
                "保存": function () {
                    if($("#m_userCode").val() == '') {
                        $(".userValidateTips").text("用户代码是必须的.");
                        $("#m_userCode").focus();
                        return false;
                    }

                    if($("#m_fullName").val() == '') {
                        $(".userValidateTips").text("用户全名是必须的.");
                        $("#m_fullName").focus();
                        return false;
                    }

                    if($("#m_loginName").val() == '') {
                        $(".userValidateTips").text("登陆名称是必须的.");
                        $("#m_loginName").focus();
                        return false;
                    }

                    if($("#m_branchId").val() == '') {
                        $(".userValidateTips").text("机构是必须的.");
                        $("#m_branchId").focus();
                        return false;
                    }
                    if($("#m_userStatus").val() == '') {
                        $(".userValidateTips").text("状态是必须的.");
                        $("#m_userStatus").focus();
                        return false;
                    }
                    
                    $.ajax({
                        url: "${ctx}/system/user/duplicate/" + $("#m_loginName").val(),
                        data: {"random": new Date().getTime()},
                        success: function (data) {
                            if(data != '' && data != $("#m_userId").val()) {
                                $(".userValidateTips").text("登陆名称重复，请重新输入.");
                                $("#m_loginName").focus();
                                return false;
                            } else {
                                $.ajax({
                                    url: "${ctx}/system/user/save",
                                    type: "post",
                                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                                    data: {"m_userId": $("#m_userId").val(),
                                        "m_userCode": $("#m_userCode").val(),
                                        "m_fullName": $("#m_fullName").val(),
                                        "m_loginName": $("#m_loginName").val(),
                                        "m_phone": $("#m_phone").val(),
                                        "m_branchId": $("#m_branchId").val(),
                                        "m_userStatus": $("#m_userStatus").val(),
                                        //"m_orgId": $("#m_orgId").val(),
                                        // "m_orgCode": $("#m_orgCode").val(),
                                        // "m_orgName": $("#m_orgName").val(),
                                        // "m_post": $("#m_post").val(),
                                        "random": new Date().getTime()},
                                    success: function (data) {
                                        $("#userForm").submit();
                                    }
                                });
                            }
                        }
                    });
                },
                "取消": function () {
                    $(this).dialog("close");
                }
            }
        });
        
        $("#assign-role-dialog-form").dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            buttons: {
                "保存": function () {
                    $("input[name='m_roleIds']").each(function(){
                        if($(this).prop("checked")) {
                            $("#m_hRoleIds").val($("#m_hRoleIds").val() + ',' + $(this).val());
                        }
                    });
                    if($("#m_hRoleIds").val() == '') {
                        $("#m_hRoleIds").val("0");
                    }

                    $(this).dialog("close");
                    $.ajax({
                        url: "${ctx}/system/user/role/assign/" + $("#m_userId").val() + "/" + $("#m_hRoleIds").val(),
                        data: {"random": new Date().getTime()},
                        success: function (data) {
                            $("#userForm").submit();
                        }
                    });
                },
                "关闭": function () {
                    $(this).dialog("close");
                }
            }
        });
        
        $("#reset-pwd-dialog-form").dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            buttons: {
                "重置密码": function () {
                    $(this).dialog("close");
                    $.ajax({
                        url: "${ctx}/system/resetPassword",
                        data: {"m_id": $("#m_userId").val(), "random": new Date().getTime()},
                        success: function (data) {
                            $("#userForm").submit();
                        }
                    });
                },
                "关闭": function () {
                    $(this).dialog("close");
                }
            }
        });
    });
    
    function deleteUser(id){
    	$.confirm(function(){
    		$.ajax({
                url: "${ctx}/system/user/delete",
                data: {"m_userId": id, "random": new Date().getTime()},
                success: function (data) {
                	if (data == 'self') {
                        $.prompt("不能删除自己.");
                        return false;
                    } else if (data == 'lastAdmin') {
                    	$.prompt("已经是最后一个管理员账号，不能再被删除.");
                        return false;
                    } else {
                        $("#userForm").submit();
                    }
                }
            });
        })
    }
    
    function assignRole(id) {
        $("#m_userId").val(id);
        $("#m_hRoleIds").val("");
        $("input[name='m_roleIds']").removeAttr("checked");

        $.ajax({
            url: "${ctx}/system/user/role/" + $("#m_userId").val(),
            data: {"random": new Date().getTime()},
            dataType: "json",
            success: function (roles) {
                $("#assign-role-dialog-form").dialog("open");
                for(i = 0; i < roles.length; i++) {
                    $("input[name='m_roleIds']").each(function(){
                        if($(this).val() == roles[i]) {
                            $(this).attr("checked", "true");
                            $(this).prop("checked", "true");
                        }
                    });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                onAsyncError();
            }
        })
    }
    
    function resetPassword(id) {
        $("#m_userId").val(id);
        $("#reset-pwd-dialog-form").dialog("open");
    }
  	//=========================MJWL END======================
</script>
<!-- <div style="display:none" id="pageMenu" firstLevelMenuId="1", secondLevelMenuId="7"></div> -->
<%-- <ol class="breadcrumb">
    <li><a href="${ctx}/home"><span  class="fa fa-home fa-fw"></span></a></li>
    <li><a href="#">System Settings</a></li>
    <li class="active"><a href="#">User Management</a></li>
</ol> --%>


<div class="panel_container">
    <div class="panel">
        <form name="userForm" id="userForm" action="" method="POST">
        <div class="panel_header">
            <div><h2>用户管理</h2></div>
        </div>
        <div class="panel_body">
            <div>
                <div class="info_item"><span>登陆名称:</span><input type="text" name="loginName" id="loginName"/></div>
                <div class="info_item"><span>机构代码:</span><input type="text" name="orgCode" id="orgCode"/></div>
            </div>
        </div>
        <div class="panel_footer">
            <div>
                <input type="button" value="查询" id="btn_search"/>&nbsp;
                <input type="button" value="创建用户" id="btn_createUser" onclick="addUser()"/>&nbsp;
            </div>
        </div>
        </form>
    </div>

    <div class="panel">
        <div class="panel_body">
            <div>
                <table id="userList"></table>
                <div id="pager"></div>
            </div>
        </div>
    </div>
</div>


<div id="user-dialog-form" title="用户信息" style="display: none;">
    <p>提示：登陆密码默认为 123@abc.</p>
    <input type="hidden" id="m_userId" name="m_userId"/>
    <p class="userValidateTips ui-state-highlight"></p>
    <table class="searchtable">
        <tbody>
        <tr>
            <td class="bg_gray">用户代码(<font color="red">*</font>)</td>
            <td>
                <input type="text" name="m_userCode" id="m_userCode" maxlength="20"
                       class="form-control"/>
            </td>
        </tr>

        <tr>
            <td class="bg_gray">用户全名(<font color="red">*</font>)</td>
            <td>
                <input type="text" name="m_fullName" id="m_fullName" maxlength="25"
                       class="form-control"/>
            </td>
        </tr>

        <tr>
            <td class="bg_gray">登陆名称(<font color="red">*</font>)</td>
            <td>
                <input type="text" name="m_loginName" id="m_loginName" maxlength="10"
                       class="form-control" onblur="checkDuplicate(this.value)"/>
            </td>
        </tr>

        <tr>
            <td class="bg_gray">电话</td>
            <td>
                <input type="text" name="m_phone" id="m_phone" maxlength="20"
                       class="form-control"/>
            </td>
        </tr>
        
        <tr>
            <td class="bg_gray">机构(<font color="red">*</font>)</td>
            <td>
                <select name="m_branchId" id="m_branchId">
                    <option value="">--请选择--</option>
                    <c:forEach var="entry" items="${orgList}">
                        <option value="${entry.id}" >${entry.orgName}</option>
                    </c:forEach>
                </select>
            </td>
        </tr>
        <tr>
            <td class="bg_gray">状态(<font color="red">*</font>)</td>
            <td>
                <select  name="m_userStatus" id="m_userStatus">
                    <option  value="" >请选择
                    <option  value="1" selected>激活
                    <option  value="2">冻结
                </select>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<div id="assign-role-dialog-form" title="分配角色" style="display: none;">
    <p class="roleValidateTips"></p>
    <div>
        <input type="hidden" name="m_hRoleIds" id="m_hRoleIds" />
        <c:forEach items="${roles}" var="role">
        	<c:if test="${role.value != 1}">
            <input type="checkbox" name="m_roleIds" value="${role.value}"/> ${role.label} <br />
            </c:if>
        </c:forEach>
    </div>
</div>

<div id="reset-pwd-dialog-form" title="重置密码" style="display: none;">
    设置默认密码: ${defaultPassword}
</div>

<div id="menuContent" class="menuBackground" style="display:none; position: absolute;">
    <ul id="tree" class="ztree selectTree"></ul>
</div>
